package com.demos.springcloud.consumer01RestTemplate.RestTemplate;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@RestController
@RequestMapping("consumer")
public class controller {
    @Autowired
    private RestTemplate restTemplate;

    @Value("${ProviderHost.get}")
    private String getHost;

    @Value("${ProviderHost.post}")
    private String postHost;

    @GetMapping("get/{id}")
    @ResponseBody
    public Map<String, Object> doGet(@PathVariable String id){
        String url = "http://"+getHost+"/get/data/"+id;
        Map<String, Object> data = restTemplate.getForObject(url, Map.class);
        return data;
    }

    @GetMapping("post/{id}")
    @ResponseBody
    public Map<String, Object> doPost(@PathVariable String id){
        HttpHeaders headers = new HttpHeaders();
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>();
        body.add("id", id);
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(body, headers);
        String url = "http://"+postHost+"/post/data";
        Map<String, Object> data = restTemplate.postForObject(url, entity, Map.class);
        return data;
    }
}
